package com.zhoujian.Observer.asyc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WeatherStation implements Subject {
    //气温
    private float temperature;

    private ExecutorService executorService;

    public WeatherStation(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public WeatherStation() {
    }

    //应该持有多个观察者
    private List<Observer> observers = new ArrayList<>();
    public void changeTemperature(float newTemperature){
        this.temperature = newTemperature;
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {

    }


    @Override
    public void notifyObservers(float newTemperature) {

        if (executorService == null){
            //这里产生的阻塞
        for (Observer observer : observers) {
            observer.update(newTemperature);
        }
        }else {
            //如果传递了线程池，就异步通知
            for (Observer observer : observers) {
                new Thread(()->{
                    observer.update(newTemperature);
                }).start();
            }
        }
    }
}
